package com.wxxymaker.edu.service;

import com.blade.ioc.annotation.Bean;
import com.wxxymaker.edu.model.entity.PracticeResponse;
import com.wxxymaker.edu.utils.TimeUtils;
import io.github.biezhi.anima.Anima;

/**
 * @AUTHOR soft
 * @DATE 2018/10/13 16:24
 * @DESCRIBE
 */
@Bean
public class PracticeResponseService implements Service<PracticeResponse> {

    /**
     * 根据题目id和用户id获取用户作答
     * @param pid 题目id
     * @param uid 用户id
     */
    public PracticeResponse findByPidAndUid(int pid, int uid) {
        return Anima.select().from(PracticeResponse.class)
                .where(PracticeResponse::getPracticeId, pid)
                .where(PracticeResponse::getUserId, uid)
                .one();
    }

    @Override
    public PracticeResponse add(PracticeResponse practiceResponse) {
        practiceResponse.setTime(TimeUtils.getTime());
        Integer integer = practiceResponse.save().asInt();
        if (integer>0) {
            practiceResponse.setId(integer);
            return practiceResponse;
        }
        return null;
    }

    @Override
    public PracticeResponse delete(Object pk) {
        PracticeResponse practiceResult = byId(pk);
        if (practiceResult!=null){
            practiceResult.delete();
            return practiceResult;
        }
        return null;
    }

    public PracticeResponse resubmit(PracticeResponse practiceResponse) {
        Integer id = practiceResponse.getId();
        if (this.change(practiceResponse)) {
            practiceResponse.setId(id);
            return practiceResponse;
        }
        return null;
    }

    @Override
    public boolean change(PracticeResponse practiceResponse) {
        if (practiceResponse.getId()>0) {
            return practiceResponse.update() > 0;
        }
        return false;
    }

    @Override
    public PracticeResponse byId(Object pk) {
        return Anima.select().from(PracticeResponse.class).byId(pk);
    }

    public Long countByUid(Integer userId) {
        return Anima.select().from(PracticeResponse.class)
                .where(PracticeResponse::getUserId, userId)
                .count();
    }

    public int deleteByPid(Integer pid) {
        return Anima.delete().from(PracticeResponse.class)
                .where(PracticeResponse::getPracticeId, pid)
                .execute();
    }
}
